package model

import (
	"fmt"
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"log"
)

type Figure struct {
	Img         *ebiten.Image
	speedFactor int
	jumpVy      float64
	jumpSpeed   int
	gravity     float64 //重力加速度
	cfg         *Config
	*Entity
}

var (
	img      *ebiten.Image
	jumpImg  *ebiten.Image
	rightImg *ebiten.Image
)

func loadImages() {
	// 加载初始图像
	var err error
	rightImg, _, err = ebitenutil.NewImageFromFile("static/img/right.png")
	if err != nil {
		fmt.Println("图片找不到")
		log.Fatal(err)
	}

	// 加载跳跃图像
	jumpImg, _, err = ebitenutil.NewImageFromFile("static/img/figure.png")
	if err != nil {
		log.Fatal(err)
	}
	img = rightImg
}

func (figure *Figure) Move() {
	//if ebiten.IsKeyPressed(ebiten.KeyRight) {
	//	figure.x += float64(figure.speedFactor)
	//}
	//限制出界
	//if figure.x < 0 {
	//	figure.x = 0
	//}
	//if figure.x > float64(figure.cfg.ScreenWidth-figure.width/2) {
	//	figure.x = float64(figure.cfg.ScreenWidth - figure.width/2)
	//}

	//跳跃
	if ebiten.IsKeyPressed(ebiten.KeySpace) {
		SpacePressed = true
	} else {
		SpacePressed = false
	}
	if SpacePressed && !IsJumping && SpaceReleased {
		figure.jumpVy = -float64(figure.jumpSpeed)
		IsJumping = true
	}
	if IsJumping {
		img = jumpImg
		figure.Y += figure.jumpVy
		figure.jumpVy += figure.gravity
		if figure.Y > float64(figure.cfg.ScreenHeight-figure.Height) {
			figure.Y = float64(figure.cfg.ScreenHeight - figure.Height)
			figure.jumpVy = 0
			IsJumping = false
			SpaceReleased = true
		}
	} else {
		img = rightImg
		SpaceReleased = true
	}
}

func NewFigure(config *Config) *Figure {
	loadImages()
	Width, Height := img.Bounds().Dx(), img.Bounds().Dy()
	f := &Figure{
		Img:         img,
		speedFactor: config.SpeedFactor,
		jumpVy:      -float64(config.JumpSpeedFactor),
		jumpSpeed:   config.JumpSpeedFactor,
		gravity:     config.Gravity,
		cfg:         config,
		Entity: &Entity{
			Width:  Width,
			Height: Height,
			X:      float64(Width),
			Y:      float64(config.ScreenHeight - Height),
		},
	}
	return f
}

var (
	SpacePressed  = false
	SpaceReleased = true
	IsJumping     = false
)

func (figure *Figure) Draw(screen *ebiten.Image, config *Config) {
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(figure.X, figure.Y)
	screen.DrawImage(img, op)
	//screen.DrawImage(figure.Img, op)
}
